import { computed, reactive, ref } from 'vue';
import { baseConfirm } from './use-message';
interface UseTableOptions {
  confirm?: any,
  del?: (data: any) => any;
  onSuccess?: () => any,
  onError?: () => any,
}

/** useDel: 删除通用hooks */
export const useDel = (options: UseTableOptions) => {
  const {
    confirm: optConfirm,
    del,
    onSuccess,
    onError
  } = options;

  const state: any = {
    currentData: null
  };
  const useConfirm = optConfirm !== false;
  const onClickDel = async (data: any) => {
    if (typeof del !== 'function') return;
    if (useConfirm) {
      let options: any = {};
      if (typeof optConfirm === 'string' || typeof optConfirm === 'number') {
        options = { message: optConfirm };
      } else if (typeof optConfirm === 'function') {
        options = optConfirm(data);
      } else if (Object.prototype.toLocaleString.call(optConfirm) === '[object Object]') {
        options = optConfirm;
      }
      await delConfirm(options);
    }

    state.currentData = data;
    const { err } = await del(data) || {};
    if (err && typeof onError === 'function') {
      onError();
    } else if (typeof onSuccess === 'function') {
      onSuccess();
    }
  };

  return {
    state,
    onClickDel
  };
};

export const delConfirm = (options: any = {}) => {
  return baseConfirm({
    message: '确认删除该数据？',
    type: 'error',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    ...options
  });
};
